#include "qcolorgradient.h"
#include <QDebug>

QColorGradient::QColorGradient()
{
}

QColorGradient::~QColorGradient()
{
}

void QColorGradient::setColorAt(double d, QColor c)
{
    colorMap.insert(d, c);
}

QList<QColor> QColorGradient::getColorList(int coloLen)
{
    QList<QColor> list;

    if (colorMap.size() == 0) {
        colorMap.insert(0, QColor(Qt::red));
    } else {
        if (!colorMap.contains(0)) {
            colorMap.insert(0, colorMap.first());
        }
        if (!colorMap.contains(1)) {
            colorMap.insert(1, colorMap.last());
        }
    }

    QList<QColor> colorList;
    QList<int> indexList;
    for (QMap<double, QColor>::iterator itor = colorMap.begin(); itor != colorMap.end(); ++itor) {
        indexList.append(itor.key() * coloLen);
        colorList.append(itor.value());
    }

    for (int i = 0; i < colorList.size() - 1; i++) {
        QColor beginColor = colorList.at(i);
        QColor endColor = colorList.at(i + 1);
        int colorBand = indexList.at(i + 1) - indexList.at(i);
        for (int j = 0; j < colorBand; j++) {
            float p = j / float(colorBand);
            list.append(QColor(int((1.0 - p) * beginColor.red() + p * endColor.red() + 0.5),
                int((1.0 - p) * beginColor.green() + p * endColor.green() + 0.5),
                int((1.0 - p) * beginColor.blue() + p * endColor.blue() + 0.5)));
        }
    }
    //qDebug() << list.size();
    return list;
}

void QColorGradient::setColorMap(const QMap<double, QColor>& value)
{
    colorMap = value;
}
